<template>
  <div>
    <el-breadcrumb separator="/" separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/admin' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/admin/menu/list">菜单管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>菜单列表</el-breadcrumb-item>
    </el-breadcrumb><br><br>

    &nbsp;&nbsp;&nbsp;&nbsp;
    标题：
    <el-input placeholder="标题"
              v-model="input.name"
              clearable
              @input="listMenusByCondition()"
              style="width: 200px;"></el-input>
    &nbsp;&nbsp;&nbsp;&nbsp;
    菜单地址：
    <el-input placeholder="菜单地址"
              v-model="input.value"
              clearable
              @input="listMenusByCondition()"
              style="width: 200px;"></el-input>
    &nbsp;&nbsp;&nbsp;&nbsp;
    时间：
    <el-date-picker
        v-model="updateTimeQuery"
        type="daterange"
        align="right"
        unlink-panels
        range-separator="至"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        :picker-options="pickerOptions"
        @change="listMenusByCondition()">
    </el-date-picker>
    &nbsp;&nbsp;&nbsp;&nbsp;
    <el-button type="primary" icon="el-icon-search" @click="listMenusByCondition()">搜索</el-button>
    <br><br>

    <el-button type="primary" round @click="cardPopup(0)" style="margin: 0 0 15px 0">创建</el-button>


    <el-dropdown>
      <el-button type="primary" round style="margin-left: 10px">{{ menuStatusButton }}</el-button>
      <el-dropdown-menu slot="dropdown">
        <a href="javascript:void(0)" @click="queryStatus(1)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>正常使用</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryStatus(2)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>禁用状态</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryStatus(3)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>全部状态</el-dropdown-item>
        </a>
      </el-dropdown-menu>
    </el-dropdown>


    <el-dropdown>
      <el-button type="primary" round style="margin-left: 10px">{{ privilegeLevel }}</el-button>
      <el-dropdown-menu slot="dropdown">
        <a href="javascript:void(0)" @click="queryLevel(1)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>一级菜单</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryLevel(2)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>二级菜单</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryLevel(3)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>三级菜单</el-dropdown-item>
        </a>
        <a href="javascript:void(0)" @click="queryLevel(4)" style="text-decoration:none;color: #606266">
          <el-dropdown-item>全部菜单</el-dropdown-item>
        </a>
      </el-dropdown-menu>
    </el-dropdown>


    <el-button type="danger" round style="float: right" @click="handleDeleteList()">批量删除</el-button>


    <template>
      <el-table
          :data="tableData"
          ref="multipleTable"
          border
          style="width: 100%"
          @selection-change="handleSelectionChange">
        <el-table-column
            type="selection"
            width="40">
        </el-table-column>
        <el-table-column fixed prop="id" label="ID" width="70"></el-table-column>
        <el-table-column fixed prop="name" label="菜单标题" width="150"></el-table-column>
        <el-table-column fixed prop="value" label="菜单地址" width="200"></el-table-column>
        <el-table-column fixed prop="description" label="菜单描述" width="200"></el-table-column>
        <el-table-column fixed prop="gmtCreate" label="创建时间" width="160"></el-table-column>
        <el-table-column fixed prop="gmtModified" label="更新时间" width="160"></el-table-column>
        <el-table-column fixed prop="status" label="菜单状态" width="100">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" :content="scope.row.status==1?'已启用':'已禁用'">
              <el-switch
                  v-model="scope.row.status"
                  active-color="#13ce66"
                  inacti
                  :active-value="1"
                  :inactive-value="0"
                  @change="handleEdit(scope.row)">
              </el-switch>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            width="120">
          <template slot-scope="scope" style="float: left">
            <el-button type="primary" icon="el-icon-edit" circle
                       @click="cardPopup(scope.row.id);
                       selectById(scope.row.id)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle
                       @click="handleDelete(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
    </template>


    <!--添加/修改弹窗-->
    <template>
      <el-dialog
          append-to-body
          :title=dialogVisibleTitle
          :visible.sync="dialogVisible"
          :close-on-click-modal="false"
          :close-on-press-escape="false"
          width="40%"
          @close="closeDialog('ruleForm')">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="180px" class="demo-ruleForm">

          <el-form-item label="菜单标题" prop="name">
            <el-input v-model="ruleForm.name" maxlength="15" show-word-limit clearable
                      style="width: 300px;" placeholder="请输入标题"></el-input>
          </el-form-item>

          <el-form-item label="菜单地址" prop="value">
            <el-input v-model="ruleForm.value" maxlength="50" show-word-limit clearable
                      style="width: 300px;" placeholder="请输入地址"></el-input>
          </el-form-item>

          <el-form-item label="菜单级别" prop="depth">
            <el-button disabled style="text-align:center;width: 140px">默认创建一级菜单</el-button>
            <el-button
                type="primary"
                @click="drawer = true;
                menuPopups()"
                style="float: right;margin-right: 100px">
              {{ menuParentName }}
            </el-button>
          </el-form-item>

          <el-form-item label="菜单描述" prop="description">
            <el-input
                type="textarea"
                placeholder="这里可以畅所欲言哦~"
                v-model="ruleForm.description"
                maxlength="30"
                style="width:300px"
                show-word-limit>
            </el-input>
          </el-form-item>

          <el-form-item label="是否启用" prop="status">
            <el-tooltip :content="ruleForm.status=='1'?'启用':'禁用'" placement="top">
              <el-switch
                  v-model="ruleForm.status"
                  active-color="#13ce66"
                  inactive-color="#E4E7ED"
                  :active-value="1"
                  :inactive-value="0"
              ></el-switch>
            </el-tooltip>

            <!--自定义排序-->
            <input class="sortButtonInput"
                   type="text"
                   plain
                   id="myInput"
                   autocomplete=”off”
                   v-if="this.isDisplaySortInput"
                   v-model="ruleForm.sort"/>
            <el-button
                type="primary"
                style="float: right;margin-right: 100px"
                @click="sortButtonMethod()">
              {{ sortButtonName }}
            </el-button>

          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="submitForm()">提交</el-button>
            <el-button @click="closeDialog('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-dialog>
    </template>


    <!--权限树列表-->
    <template>
      <el-drawer
          title="权限菜单"
          append-to-body
          :before-close="handleClose"
          :visible.sync="drawer"
          direction="rtl"
          custom-class="demo-drawer"
          ref="drawer"
      >
        <div class="demo-drawer__content">
          <el-form ref="ruleForm" label-width="180px" class="demo-ruleForm">
            <el-tree
                :data="treeData"
                ref="tree"
                show-checkbox
                node-key="key"
                check-strictly="true"
                :default-expanded-keys=[0]
                @check-change="handleClick"
                :default-checked-keys=romeMenuEchoArray
                style="bottom: -10px"
                :props="defaultProps"
            />
          </el-form>
          <div class="demo-drawer__footer" style="position: relative;top: 30px;">
            <el-button @click="cancelForm">取 消</el-button>
            <el-button
                type="primary"
                @click="handleCloses"
            >确 定
            </el-button>
          </div>
        </div>
      </el-drawer>
    </template>


    <!--页码-->
    <template>
      <div>
        <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[5, 10, 20]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="countDate">
        </el-pagination>
      </div>
    </template>

  </div>
</template>

<script>
export default {
  data() {
    return {
      ruleForm: {
        id: '',
        value: '',
        name: '',
        sort:'',
        description: '',
        parentId: '', // 父级id
        status: 1,
      },         // 添加 / 修改数据集
      rules: {
        name: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        sort: [
          {type: 'int', message: '请输入数字', trigger: 'blur'},
          {min: 2, max: 15, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
        value: [
          {required: true, message: '请输入地址', trigger: 'blur'},
          {min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur'}
        ],
        description: [
          {min: 2, max: 50, message: '长度在 2 到 15 个字符', trigger: 'blur'}
        ],
      },                  // 输入验证

      treeData: [],                  // 权限树数据源
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      romeMenuEchoArray: [],          //角色权限回填数组

      input: {
        value: '',
        name: '',
        description: '',
        status: 1,
        depth: '',
        updateTimeStart: '',
        updateTimeEnd: '',
        offset: '0',
        count: '5'
      },          // 查询条件
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },          // 日期查询条件
      updateTimeQuery: [],           //日期查询结果
      tableData: [],                 // 条件查询结果集
      multipleSelection: [],         // 复选框数组

      menuParentName: '点击选择父菜单',  // 父类名称
      menuStatusButton: '正常使用',    // 权限状态按钮标题
      privilegeLevel: '全部菜单',      // 权限等级
      dialogVisibleTitle: '添加用户',   // 弹框标题---【添加 or 修改功能】
      AddOrSetByMenuId: 0,           // 区别方法【添加 ro 修改】
      sortButtonName:'默认排序',             // 排序按钮
      isDisplaySortInput: false,              // 自定义排序按钮
      dialogVisible: false,          // 弹出框状态(添加 or 修改功能)，默认隐藏
      drawer: false,                 // 弹出框状态(权限树列表)，默认隐藏
      props: {multiple: true},       // 默认弹窗的默认设置

      currentPage: 1,         // 当前页码
      currentSize: 5,         // 每页展示信息数量
      countDate: 0,           // 条件查询结果集数量
    }
  },
  methods: {

    /**
     * 弹窗：添加 OR 修改
     */
    cardPopup(menuId) {
      if (menuId === 0) {
        this.ruleForm.status = 1;             // 默认角色状态为启用
        this.AddOrSetByMenuId = 0;            // 调用添加方法
        this.dialogVisibleTitle = "添加菜单";   // 设置弹窗标题
      } else {
        this.dialogVisibleTitle = "修改菜单";
        this.AddOrSetByMenuId = menuId;       // 调用修改方法
        // this.$refs.tree.setCheckedKeys([this.ruleForm.parentId])  TODO：单选框回显不了
      }
      this.dialogVisible = true;              // 打开弹窗
    },


    /**
     * 业务：添加 OR 修改
     */
    submitForm() {
      let addOrSetData = this.ruleForm;
      if (this.AddOrSetByMenuId === 0) {
        let path = "http://localhost:9090/system/menu/createMenu"
        console.log("即将发送【新增权限】请求：参数{" +
            "value=" + addOrSetData.value + "，" +
            "name=" + addOrSetData.name + "，" +
            "sort=" + addOrSetData.sort + "，" +
            "description=" + addOrSetData.description + "，" +
            "parentId=" + addOrSetData.parentId + "，" +
            "status=" + addOrSetData.status +
            "}")
        this.axios.post(path, addOrSetData).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: "创建成功"
              });
              this.listMenusByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      } else {
        let path = "http://localhost:9090/system/menu/updateById"
        console.log("即将发送【修改权限】请求：参数{" +
            "id=" + addOrSetData.id + "，" +
            "value=" + addOrSetData.value + "，" +
            "name=" + addOrSetData.name + "，" +
            "sort=" + addOrSetData.sort + "，" +
            "description=" + addOrSetData.description + "，" +
            "parentId=" + addOrSetData.parentId + "，" +
            "status=" + addOrSetData.status +
            +"}")
        this.axios.post(path, addOrSetData).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '修改用户成功!'
              });
              this.listMenusByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              })
              break;
          }
        })
      }

      this.dialogVisible = false;
      this.closeDialog();
    },


    /**
     * 业务：更换父级id
     * 按钮：提交按钮---权限树列表弹窗
     */
    handleCloses(done) {
      this.ruleForm.parentId = this.$refs.tree.getCheckedNodes()[0].key;
      if (this.ruleForm.parentId === this.ruleForm.id) {
        this.$message({
          type: 'error',
          message: "不能选择自己为父级权限"
        });
      } else {
        this.axios.get("http://localhost:9090/system/menu/isViolationMenuTree?menuId=" + this.ruleForm.id + "&parentId=" + this.ruleForm.parentId).then((response) => {
          if (response.data.code) {
            this.menuParentName = this.$refs.tree.getCheckedNodes()[0].label;
            this.drawer = false;
          } else {
            this.$message({
              type: 'error',
              message: response.data.message
            });
          }
        })
      }
    },


    /**
     * 业务：修改权限状态
     * @param id
     */
    handleEdit(row) {
      let data = this.ruleForm;
      let temp = '';  // 自定义修改状态提示
      this.axios.get("http://localhost:9090/system/menu/isSonMenuById?id=" + row.id).then((response) => {
        if (response.data.code == 200) {
          if (row.status === 1) {
            temp = '此操作将启用【' + row.name + ',及其子级】权限, 是否继续?'
          } else {
            temp = '此操作将使【' + row.name + ',及其子级】权限无法使用, 是否继续?'
          }
        } else {
          if (row.status === 1) {
            temp = '此操作将启用【' + row.name + '】权限, 是否继续?'
          } else {
            temp = '此操作将使【' + row.name + '】权限无法使用, 是否继续?'
          }
        }


        this.$confirm(temp, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let path = "http://localhost:9090/system/menu/switchPermission"
          let data = {
            id: row.id,
            value: row.value,
            name: row.name,
            description: row.description,
            parentId: row.parentId,
            status: row.status
          }
          this.axios.post(path, data).then((response) => {
            switch (response.data.code) {
              case 200:
                // then.$message({
                //   type: 'success',
                //   message: "修改成功"
                // })
                this.listMenusByCondition();
                break;
              default:
                this.$message({
                  type: 'error',
                  message: response.data.message
                })
                if (row.status == 0) {
                  row.status = 1;
                } else {
                  row.status = 0;
                }
                break;
            }
          })
        }).catch(() => {
          if (row.status == 0) {
            row.status = 1;
          } else {
            row.status = 0;
          }
        })
      })
    },


    /**
     * 业务：删除
     * @param id
     */
    handleDelete(row) {
      this.$confirm('此操作将永久删除【' + row.name + '】, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        console.log("即将执行删除【" + row.name + "】")
        this.axios.post("http://localhost:9090/system/menu/deleteById", row).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.listMenusByCondition();
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              });
              break;
          }
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },


    /**
     * 业务：批量删除
     */
    handleDeleteList() {
      if (this.multipleSelection.length < 1) {
        this.$message({
          type: 'info',
          message: '请勾选需要删除的品牌'
        });
        return;
      }
      let array = [];
      for (let i = 0; i < this.multipleSelection.length; i++) {
        array.push(this.multipleSelection[i].id);
      }

      this.$confirm('此操作将永久删除id为【' + array + '】的权限, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.axios.post("http://localhost:9090/system/menu/deleteByIds", array).then((response) => {
          switch (response.data.code) {
            case 200:
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.listMenusByCondition()
              break;
            default:
              this.$message({
                type: 'error',
                message: response.data.message
              });
              break;
          }
        })
      }).catch(() => {
        this.$refs.multipleTable.clearSelection();
        this.$message({
          type: 'info',
          message: '已取消批量删除'
        });
      });
    },


    /**
     * 业务：获取批量删除业务选中的复选框
     * @param val
     */
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },


    /**
     * 条件查询，返回结果集
     */
    listMenusByCondition() {

      // 获取时间搜索的条件
      if (this.updateTimeQuery != null) {
        this.input.updateTimeStart = this.updateTimeQuery[0];
        this.input.updateTimeEnd = this.updateTimeQuery[1];
      } else {
        this.input.updateTimeStart = null;
        this.input.updateTimeEnd = null;
      }

      let then = this
      // 条件查询，返回结果集数量
      this.axios.post("http://localhost:9090/system/menu/getCountAll", this.input).then((response) => {
        this.countDate = response.data;
        let temp = response.data;
        if (response.data>0){
          let tempPageNum = temp%this.currentSize===0?temp/this.currentSize:temp/this.currentSize+1;
          if(then.currentPage > tempPageNum){
            then.input.offset = 0;
            then.currentPage = 1;
          }
          this.input.offset = (this.currentPage - 1) * this.currentSize;
          this.input.count = this.currentSize;

          // 条件查询结果集
          then.axios.post("http://localhost:9090/system/menu/listMenusByCondition", then.input).then((response) => {
            then.tableData = response.data;
          })
        }else {
          this.tableData = ''
        }
      })
    },


    /**
     * 业务：查询权限树数据源
     */
    menuPopups() {
      // 查询权限树
      this.axios.get("http://localhost:9090/system/menu/getTreeVOAll").then((response) => {
        let newList = []; //定义一个新数组用来存放遍历的数据
        let jsonObjs = response.data.data.categories;
        for (let i = 0; i < jsonObjs.length; i++) {
          newList[i] = {
            key: jsonObjs[i].id,
            label: jsonObjs[i].name,
            children: jsonObjs[i].childrens
          };

          // 二级数据
          let jsonObjs2 = jsonObjs[i].childrens;
          if (jsonObjs2 != null) {
            for (let j = 0; j < jsonObjs2.length; j++) {
              newList[i].children[j] = {
                key: jsonObjs2[j].id,
                label: jsonObjs2[j].name,
                children: jsonObjs2[j].childrens
              };

              // 三级数据
              let jsonObjs3 = newList[i].children[j].children
              if (jsonObjs3 != null) {
                for (let k = 0; k < jsonObjs3.length; k++) {
                  newList[i].children[j].children[k] = {
                    key: jsonObjs3[k].id,
                    label: jsonObjs3[k].name,
                    children: jsonObjs3[k].children
                  };
                }
              }
            }
          }
        }
        this.treeData = newList;
      })
    },


    /**
     * 查询全部状态权限
     */
    queryStatus(id) {
      switch (id) {
        case 1:
          this.menuStatusButton = '正常使用';
          this.input.status = 1;
          break;
        case 2:
          this.menuStatusButton = '禁用状态';
          this.input.status = 0;
          break;
        case 3:
          this.menuStatusButton = '全部状态';
          this.input.status = null;
          break;
      }
      this.listMenusByCondition();
    },


    /**
     * 查询全部状态账户
     */
    queryLevel(depth) {
      switch (depth) {
        case 1:
          this.privilegeLevel = '一级菜单';
          this.input.depth = 1;
          break;
        case 2:
          this.privilegeLevel = '二级菜单';
          this.input.depth = 2;
          break;
        case 3:
          this.privilegeLevel = '三级菜单';
          this.input.depth = 3;
          break;
        case 4:
          this.privilegeLevel = '所有菜单';
          this.input.depth = null;
          break;
      }
      this.listMenusByCondition();
    },


    /**
     * 按钮：叉---权限列表弹窗
     */
    handleClose() {
      this.drawer = false;
    },


    /**
     * 按钮：取消按钮---权限列表弹窗
     */
    cancelForm() {
      this.drawer = false;
    },


    /**
     * 功能：权限树实现单选
     */
    handleClick(data, checked, node) {
      if (checked) {
        this.$refs.tree.setCheckedNodes([data]);
      }
    },


    /**
     * 按钮：自定义排序
     */
    sortButtonMethod() {
      if (this.isDisplaySortInput) {
        this.sortButtonName = '默认排序'
        this.isDisplaySortInput = false;
      } else {
        this.sortButtonName = '排序参数'
        this.isDisplaySortInput = true;
      }
    },


    /**
     * 根据id查询数据，用户回填
     * @param id
     */
    selectById(id) {
      console.log("根据id查询数据，权限回填")
      this.axios.get("http://localhost:9090/system/menu/getBackFillById?id=" + id).then((response) => {
        this.ruleForm = response.data;
        // this.ruleForm.parentId=null;
        console.log("【角色信息回显】：参数{" +
            "value=" + this.ruleForm.value + "，" +
            "name=" + this.ruleForm.name + "，" +
            "description=" + this.ruleForm.description + "，" +
            "parentId=" + this.ruleForm.parentId + "，" +
            "status=" + this.ruleForm.status +
            "}")

      })
    },


    /**
     * 分页，每页条数
     * @param val
     */
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.currentSize = val;
      this.listMenusByCondition();
    },


    /**
     * 页码超链接，当前页数
     * @param val
     */
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.listMenusByCondition();
    },


    closeDialog(ruleForm) {
      this.ruleForm = {}
      this.isDisplaySortInput = false;
      if (this.$refs[ruleForm] !== undefined) {
        this.$refs[ruleForm].resetFields();
      }
    },
  },
  created() {
    this.listMenusByCondition();
  }
}
</script>

<style>

.sortButtonInput{
  font-size:16px;
  color:#409EFF;
  text-align:center;
  width: 80px;
  height: 36px;
  position: relative;
  left: 76px;
  border-radius:10%;
  border: 1px solid #C0C4CC;
}



</style>
